package com.youhong.teethcare;

import android.app.Activity;
import android.app.Dialog;
import android.app.Instrumentation;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.dialogs.BrushModeDialog;
import com.youhong.teethcare.dialogs.LowBatteryDialog;
import com.youhong.teethcare.javabeans.JstyleDevice;
import com.youhong.teethcare.netbeans.OtaHttpReturn;
import com.youhong.teethcare.plaque.PlaqueIntroductionActivity;
import com.youhong.teethcare.ryan.DfuTool;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.settingpage.AboutUsActivity;
import com.youhong.teethcare.settingpage.BrushHeadActivity;
import com.youhong.teethcare.settingpage.DeviceManagerActivity;
import com.youhong.teethcare.settingpage.DfuActivity;
import com.youhong.teethcare.settingpage.FeedbackActivity;
import com.youhong.teethcare.settingpage.LogOutActivity;
import com.youhong.teethcare.settingpage.NotificationManagerActivity;
import com.youhong.teethcare.settingpage.PersonalInfoActivity;
import com.youhong.teethcare.settingpage.SetBrushTimeActivity;
import com.youhong.teethcare.utils.DialogUtil;
import com.youhong.teethcare.utils.HttpJsonUtils2;
import com.youhong.teethcare.utils.ImageUtils;
import com.youhong.teethcare.utils.MyCircleHeadView;
import com.youhong.teethcare.utils.PreferencesUtils;
import com.youhong.teethcare.utils.ToastUtil;
import com.youhong.teethcare.utils.Util;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.transform.Result;

/**
 * A simple {@link Fragment} subclass.
 */
public class SettingFragment extends Fragment implements View.OnClickListener, DfuTool.DfuStateListener {

    private View viewTime;

    public SettingFragment() {
        // Required empty public constructor
    }

    private static final int REQ_DFU = 0x55f;
    static final int REQ_LOGOUT = 0x11;

    RelativeLayout rl_deviceManagement, rl_personalInformation, rl_brushTimeSetting,
            rl_brushNotification, rl_aboutUs, rl_feedback, rl_brushLoss, rl_battery, rl_ota,
            rl_chart,settingPage_rl_diy,rl_More;

    ImageView iv_portrait;
    TextView tv_signOut, tv_otaPrompt, tv_name;
    DfuTool mDfuTool;
    String downloadUrl;
    int deviceVersion, serverVersion;
    TextView tv_battery;
    ProgressDialog mDialog;
    Handler handler = new Handler();

    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_setting, container, false);
        getViews(v);

        //注册蓝牙广播监听
        //启动网络线程先于获取固件版本号执行。
        network_thread = new HandlerThread("network_Thread") {
            @Override
            protected void onLooperPrepared() {

                Log.e("NetworkThreadId:", "" + getThreadId());
            }
        };

        network_thread.start();
        handler_network = new Handler(network_thread.getLooper()) {

            @Override
            public void handleMessage(Message msg) {
                if (MSG_GET_VERSION == msg.what) {
                    //访问服务器的固件最新版本.
                    Log.e("HandlerThreadLooper:", (getLooper() == SettingFragment.this.getActivity().getMainLooper()) + "");

                    Log.e("HandlerThreadId:", Thread.currentThread().getId() + "");

                } else if (MSG_DOWNLOAD == msg.what) {


                }
            }
        };
        return v;
    }

    @Override
    public void onStop() {
        getActivity().unregisterReceiver(receiver);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        network_thread.interrupt();
        handler_network.removeCallbacksAndMessages(null);
        handler.removeCallbacksAndMessages(null);
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        System.gc();

    }


    Bitmap bitmap = null;

    @Override
    public void onStart() {
        super.onStart();

        //如果设备还未连接，就不显示任何关于OTA的提示信息。
        if (MainActivity.mDevice == null) {

            tv_otaPrompt.setVisibility(View.GONE);
            tv_battery.setVisibility(View.GONE);
        } else {

            tv_otaPrompt.setVisibility(View.VISIBLE);
            tv_battery.setVisibility(View.VISIBLE);

            if (Common.isNeedToUpdate) {
                tv_otaPrompt.setTextColor(Color.RED);
                tv_otaPrompt.setText(R.string.strings73);
            } else {
                tv_otaPrompt.setTextColor(getResources().getColor(R.color.mainColor));
                tv_otaPrompt.setText(R.string.strings72);
            }
        }

       showIcon();
        tv_name.setText(Common.userInfo.getNickName());
        tv_battery.setText(Common.battery + "%");

        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        getActivity().registerReceiver(receiver, filter);

        //给获取设备版本加上500ms的延迟，避免在网络线程初始化完成前，进行调用。
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (MainActivity.mDevice != null) {
                    MainActivity.mDevice.getBattery();

                }
            }
        }, 500);
    }

    private void getViews(View v) {


        rl_chart = v.findViewById(R.id.settingPage_rl_chart);
        viewTime = v.findViewById(R.id.viewTime);
        rl_chart.setOnClickListener(this);
        settingPage_rl_diy = v.findViewById(R.id.settingPage_rl_diy);
        settingPage_rl_diy.setOnClickListener(this);
        rl_More = v.findViewById(R.id.settingPage_rl_More);
        rl_More.setOnClickListener(this);
        tv_name = v.findViewById(R.id.settingPage_tv_name);

        tv_battery = v.findViewById(R.id.settingPage_tv_battery);
        iv_portrait = v.findViewById(R.id.settingPage_iv_portrait);

        tv_otaPrompt = v.findViewById(R.id.settingPage_tv_otaPrompt);

        rl_deviceManagement = v.findViewById(R.id.settingPage_rl_deviceManagement);
        rl_deviceManagement.setOnClickListener(this);

        rl_personalInformation = v.findViewById(R.id.settingPage_rl_personalInformation);
        rl_personalInformation.setOnClickListener(this);

        rl_brushTimeSetting = v.findViewById(R.id.settingPage_rl_brushTimeSetting);
        rl_brushTimeSetting.setOnClickListener(this);

        rl_brushNotification = v.findViewById(R.id.settingPage_rl_brushReminder);
        rl_brushNotification.setOnClickListener(this);

        rl_aboutUs = v.findViewById(R.id.settingPage_rl_aboutUs);
        rl_aboutUs.setOnClickListener(this);

        rl_feedback = v.findViewById(R.id.settingPage_rl_feedback);
        rl_feedback.setOnClickListener(this);

        tv_signOut = v.findViewById(R.id.settingPage_tv_signOut);
        tv_signOut.setOnClickListener(this);

        rl_brushLoss = v.findViewById(R.id.settingPage_rl_brushLoss);
        rl_brushLoss.setOnClickListener(this);

        rl_battery = v.findViewById(R.id.settingPage_rl_battery);

        rl_ota = v.findViewById(R.id.settingPage_rl_ota);
        rl_ota.setOnClickListener(this);
        showDeviceDisplay();
    }

    @Override
    public void onClick(View v) {

        if (v == tv_signOut) {

            Intent intent = new Intent(getContext(), LogOutActivity.class);
            startActivityForResult(intent, REQ_LOGOUT);

        }else if (v == rl_More) {

            Intent intent = new Intent(getContext(), MoreActivity.class);
            startActivity(intent);

        }  else if (v == rl_deviceManagement) {

            Intent intent = new Intent(getContext(), DeviceManagerActivity.class);
            startActivity(intent);

        } else if (v == rl_ota) {

            if (tv_otaPrompt.getText().equals(getString(R.string.strings73))) {

                Intent intent = new Intent(getContext(), DfuActivity.class);
                intent.putExtra("newVersion", serverVersion);
                startActivityForResult(intent, REQ_DFU);

                powerManager = (PowerManager) getActivity().getSystemService(Activity.POWER_SERVICE);
                wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
                wakeLock.setReferenceCounted(false);
                wakeLock.acquire();
            }

        } else if (v == rl_aboutUs) {

            Intent intent = new Intent(getContext(), AboutUsActivity.class);
            startActivity(intent);
        } else if (v == rl_feedback) {

            Intent intent = new Intent(getContext(), FeedbackActivity.class);
            startActivity(intent);

        } else if (v == rl_personalInformation) {

            Intent intent = new Intent(getContext(), PersonalInfoActivity.class);
            startActivity(intent);

        } else if (v == rl_brushLoss) {

            Intent intent = new Intent(getContext(), BrushHeadActivity.class);
            startActivity(intent);

        } else if (v == rl_brushNotification) {

            Intent intent = new Intent(getContext(), NotificationManagerActivity.class);
            startActivity(intent);
        } else if (v == rl_brushTimeSetting) {
            Intent intent = new Intent(getContext(), SetBrushTimeActivity.class);
            startActivity(intent);
        } else if (v == rl_chart) {

            Intent intent = new Intent(getContext(), PlaqueIntroductionActivity.class);
            startActivity(intent);
        }else if(v==settingPage_rl_diy){

        }
    }

    void showDeviceDisplay(){
        JstyleDevice jstyleDevice=Util.getDevice();
        boolean needShowScore=jstyleDevice.needShowScore();
        rl_brushTimeSetting.setVisibility(needShowScore?View.VISIBLE:View.GONE);
        viewTime.setVisibility(needShowScore?View.VISIBLE:View.GONE);
    }


    private List getData() {
        List<String>data=new ArrayList<>();
        String[]modes=getResources().getStringArray(R.array.brushModes);
        for(int i=0;i<modes.length;i++){
            data.add(modes[i]);
        }
        return data;
    }

    Handler handler_network = null;
    HandlerThread network_thread = null;

    @Override
    public void onStateChange(int stateCode) {

        if (stateCode == DfuTool.PROGRESS_READY) {

        } else if (stateCode == DfuTool.PROGRESS_DFU_PREPARE) {

            mDialog.setMessage(getString(R.string.strings77));

            //升级正常,Remove watchDog
            handler.removeCallbacks(runnable_OtaWatchDog);


        } else if (stateCode == DfuTool.PROGRESS_FAILED) {

            //升级失败,Remove watchDog
            handler.removeCallbacks(runnable_OtaWatchDog);

            mDialog.dismiss();
            mDialog = null;

            Toast.makeText(getContext(), R.string.strings80, Toast.LENGTH_SHORT).show();

        } else if (stateCode == DfuTool.PROGRESS_FINISHED) {

            mDialog.dismiss();
            mDialog = null;
            ((MainActivity) getActivity()).connect();

            //恢复OTA 提示文本的原来文字内容和文本颜色。
            Common.isNeedToUpdate = false;
            tv_otaPrompt.setText(R.string.strings72);
            tv_otaPrompt.setTextColor(getResources().getColor(R.color.mainColor));


            Toast.makeText(getContext(), R.string.strings79, Toast.LENGTH_SHORT).show();

        } else {
            //升级正常,Remove watchDog
            handler.removeCallbacks(runnable_OtaWatchDog);
            mDialog.setMessage(getString(R.string.strings78) + stateCode + "%");
        }
    }

    private void returnUpdate(OtaHttpReturn mReturn) {

        if (mReturn == null) {

            Toast.makeText(getContext(), R.string.strings30, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mReturn.getData() != null) {

        }

        //需要升级!


        if (mReturn.getMsgCode() == 1052) {

            downloadUrl = mReturn.getData().getUrl();
            storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            storagePath += "/" + downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1);

            serverVersion = Integer.parseInt(mReturn.getData().getVersion());

            //    Log.e("UIThreadId", "" + Thread.currentThread().getId() + "");

            //下载zip升级包
            new Thread() {
                @Override
                public void run() {
                    try {
                        HttpJsonUtils2.downloadFile(downloadUrl, storagePath, download_callback);
                    } catch (Exception exp) {


                    }
                }
            }.start();

            Message msg = handler_network.obtainMessage();
            msg.what = MSG_DOWNLOAD;
            handler_network.handleMessage(msg);

        } else if (mReturn.getMsgCode() == 1051) {


        }
    }

    private static final int MSG_DOWNLOAD = 0x55A1;
    private static final int MSG_GET_VERSION = 0x55A2;

    boolean firstTimeGetVersion = true;

    String storagePath = null;

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            if (intent.getAction() == BleService.ACTION_DATA_AVAILABLE) {

                final byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);
                if (values[0] == 0x27) {

                    Common.firmwarmVersion = (values[1] - 0x30)
                            + "." + (values[2] - 0x30) + "."
                            + (values[3] - 0x30)  + "."+(values[4] - 0x30);;
                    deviceVersion = (values[1] - 0x30) * 100 +
                            (values[2] - 0x30) * 10 +
                            (values[3]) - 0x30;

                    //从服务器获取最新固件版本号
//                    new Thread() {
//
//                        @Override
//                        public void run() {
//
//                            List<NameValuePair> params = new ArrayList<>();
//                            String deviceName=Common.userInfo.getDeviceName();
//                            String deviceType="teethcare";
//                            if(!TextUtils.isEmpty(deviceName)){
//                                if(deviceName.toLowerCase().contains("fg"))deviceType="2058";
//                            }
//                            params.add(new BasicNameValuePair("type", deviceType));
//
//                           // params.add(new BasicNameValuePair("version", "001"));
//                            params.add(new BasicNameValuePair("version", deviceVersion + ""));
//
//                            final OtaHttpReturn mReturn = HttpJsonUtils2.doGetHttpRequest_Sync(HttpJsonUtils2.URL_OTA
//                                    , params, OtaHttpReturn.class);
//                            try {
//
//                                getActivity().runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//
//                                        returnUpdate(mReturn);
//                                    }
//                                });
//                            } catch (Exception exp) {
//
//                            }
//                        }
//                    }.start();
//
//
//                    Message msg = new Message();
//                    msg.what = MSG_GET_VERSION;
//                    handler_network.handleMessage(msg);

                } else if (values[0] == 0x13) {

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(values[1]==0)return;
                            Common.battery = values[1] & 0xFF;
                            tv_battery.setText(Common.battery + "%");
                            if (Common.battery <= 20 && Common.isLowBatteryNotificationPlayed == false) {

                                LowBatteryDialog dialog = new LowBatteryDialog(SettingFragment.this.getContext());
                                dialog.show();
                            }
                        }
                    });
                  //  MainActivity.mDevice.getVersion();
                }
            }
        }
    };

    Runnable runnable_OtaWatchDog = new Runnable() {
        @Override
        public void run() {
            mDialog.dismiss();
            ToastUtil.showLongToast(getContext(), R.string.strings119);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQ_DFU && resultCode == Activity.RESULT_OK) {
            //发送0x47 OTA 指令。
            if (MainActivity.mDevice == null) {

            } else {

                MainActivity.mDevice.upgradeFirmware();
                //断开连接
                ((MainActivity) getActivity()).doomPrompt = true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ((MainActivity) getActivity()).connect();
                    }
                }, 3000);
            }


            if (mDialog == null) {
                mDialog = DialogUtil.showDialog(SettingFragment.this, R.string.strings76);
            }

            mDialog.show();
            //如果升级在30s内还处于Prepare阶段，就把Dialog 消失掉。
            handler.postDelayed(runnable_OtaWatchDog, 30000);

            mDfuTool = new DfuTool(getContext(), storagePath, SettingFragment.this);
            mDfuTool.startScan(true);
        }else if(requestCode == REQ_LOGOUT && resultCode == Activity.RESULT_OK){
            getActivity().finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    void showIcon(){
        ImageUtils.showIcon(iv_portrait);
    }
    HttpJsonUtils2.downloadCallback download_callback = new HttpJsonUtils2.downloadCallback() {
        @Override
        public void downloadOver(final boolean isSucess, final long fileSize) {

            //在界面OTA右侧提示,"有新版本供用户点击进行升级.
            if (isSucess) {

                if (serverVersion > deviceVersion) {

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Common.isNeedToUpdate = true;
                            tv_otaPrompt.setTextColor(Color.RED);
                            tv_otaPrompt.setText(R.string.strings73);
                        }
                    });
                }
            }
        }
    };


}
